﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Camera_NET;
using DevComponents.DotNetBar;
using DirectShowLib;

namespace WoSoft.PACS.Win.MyControlsNew
{
    public partial class PACSCameraOld : UserControl
    {
        #region 属性分布
        // Camera choice
        private CameraChoice _CameraChoice = new CameraChoice();

        //采集图像
        public delegate void CameraingHandler(Bitmap bmp, string fileName);

        //采集事件
        public event CameraingHandler onCameraing;

        //删除图像
        public delegate void DeleteImgHandler(string fileName);

        //删除图像事件
        public event DeleteImgHandler onDeleteImg;

        //双击图像
        public delegate void ImageDBClickHandler(Image img);

        //双击图像事件
        public event ImageDBClickHandler onDbClickImage;

        //采集设备
        Capture cam = null;

        // Default width
        int camwidth = 640;

        // Default heigth
        int camheight = 480;

        // is Runing
        bool running;

        Thread thread = null;

        ManualResetEvent camlock = new ManualResetEvent(false);

        #endregion

        public PACSCameraOld()
        {
            InitializeComponent();
            this.Load += new EventHandler(PACSCamera_Load);
            this.Disposed += new EventHandler(PACSCamera_Disposed);
        }

        void PACSCamera_Disposed(object sender, EventArgs e)
        {
            this.running = false;
            if (thread != null)
            {
                thread.Abort();
            }
        }

        //加载设备列表
        void PACSCamera_Load(object sender, EventArgs e)
        {

            //DsDevice[] capDevices;

            //// Get the collection of video devices
            //capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
            //for (int i = 0; i < capDevices.Length; ++i)
            //{
            //    this.tlsCapDevices.Items.Add(capDevices[i].Name);
            //}
            //if (this.tlsCapDevices.Items.Count > 0)
            //    this.tlsCapDevices.SelectedIndex = 0;

            // Get the pixs
            //if (this.tlsPixs.Items.Count > 0)
            //{
            //    this.tlsPixs.SelectedIndex = 0;
            //    ReSetPixs();
            //}

            try
            {
                string PixsType = WoSoft.PACS.Win.Properties.Settings.Default.PixsType;
                foreach (var item in PixsType.Split('|'))
                {
                    this.tlsPixs.Items.Add(item.ToString());
                }

                string CameraVar = WoSoft.PACS.Win.Properties.Settings.Default.CameraVar;
                var v = CameraVar.Split('|');
                // Get the pixs
                this.tlsPixs.SelectedIndex = Convert.ToInt32(v[0]);
                //默认自适应大小
                this.tlsImageSize.SelectedIndex = Convert.ToInt32(v[1]);
                //摄像头
                this.tlsCapDevices.SelectedIndex = Convert.ToInt32(v[2]);
            }
            catch
            {
                this.tlsPixs.SelectedIndex = 0;
                this.tlsImageSize.SelectedIndex = 0;
                this.tlsCapDevices.SelectedIndex = 0;
            }
        }



        private void ReSetPixs()
        {
            var text = this.tlsPixs.Text;
            var vs = text.Split('*');
            var w = vs[0];
            var h = vs[1];
            camwidth = Convert.ToInt32(w);
            camheight = Convert.ToInt32(h);
        }

        //单击事件
        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "tsbPlay":
                    Play();                 //预览图像
                    break;
                case "tsbCapture":
                    CameraImage();          //采集图像
                    break;
                case "tsbStop":             //停止采集
                    axSDK30001.Stop();
                    break;
                case "tsbColorSetting":
                    ColorSettings();       //颜色属性设置
                    break;
                case "tsbOutputSetting":
                    OutputSetting();       //参数设置2
                    break;
                case "tlsSave":
                    SaveSetting();        //参数保存
                    break;
                default:
                    break;
            }
        }

        public void Play()
        {
            ReSetPixs();
            //启动预览
            var r = this.axSDK30001.Connect(0, true, camwidth, camheight);
            //var r = this.axSDK30001.Connect(0, true, axSDK30001.Width, axSDK30001.Height);
            this.axSDK30001.VideoSource = this.tlsCapDevices.SelectedIndex;
            //this.axSDK30001.SetFullScreen(true);//2016-08-09 -----------------------------------------------------------添加

            //颜色属性设置
            string ColorSetting = WoSoft.PACS.Win.Properties.Settings.Default.ColorSetting;
            var s = ColorSetting.Split('|');
            axSDK30001.Brightness = Convert.ToInt32(s[0]);
            axSDK30001.Contrast = Convert.ToInt32(s[1]);
            axSDK30001.Saturation = Convert.ToInt32(s[2]);
            axSDK30001.Hue = Convert.ToInt32(s[3]);
            axSDK30001.Sharpness = Convert.ToInt32(s[4]);

            /*连接成功后，直接运行*/
            r = axSDK30001.Run();
        }

        //采图像
        public void CameraImage()
        {
            var ImgFloder = System.DateTime.Now.ToString("yyyyMMdd");
            var CaptureImageSavePath = Path.Combine(Application.StartupPath, "CaptureImages", ImgFloder);
            var fileName = Guid.NewGuid().ToString();
            var captureImageName = Path.Combine(CaptureImageSavePath, string.Format("{0}.jpg", fileName));
            if (!Directory.Exists(CaptureImageSavePath))
            {
                Directory.CreateDirectory(CaptureImageSavePath);
            }

            var r = this.axSDK30001.SaveImageToJpg(captureImageName, 100, 1, false);
            if (r)
            {
                var i = 0;
                while (!File.Exists(captureImageName))
                {/*等待采集完成后执行图像处理*/
                    if (i > 100)
                    {
                        break;
                    }
                    i++;
                    Thread.Sleep(100);
                }

                if (File.Exists(captureImageName))
                {
                    Bitmap bmp = new Bitmap(captureImageName);
                    AddImage(bmp, fileName);

                    //触发采集图像事件
                    if (onCameraing != null)
                    {
                        onCameraing(bmp, fileName);
                    }
                    Thread.Sleep(100);
                }
            }
        }

        /// <summary>
        /// 清除所有采集图像
        /// </summary>
        public void CleraImages()
        {
            this.panelImgs.Controls.Clear();
        }

        /// <summary>
        /// 向采集图像中添加
        /// </summary>
        /// <param name="bmp"></param>
        public void AddImage(Bitmap bmp, string fileID)
        {
            //添加到容器中
            var imgBox = new PictureBox();
            imgBox.Name = fileID;
            imgBox.SizeMode = PictureBoxSizeMode.StretchImage;
            imgBox.Height = 150;
            imgBox.Image = bmp;
            //imgBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            imgBox.MouseDown += new MouseEventHandler(imgBox_MouseDown);
            imgBox.DoubleClick += new EventHandler(imgBox_DoubleClick);
            imgBox.Margin = new System.Windows.Forms.Padding(5);
            imgBox.Padding = new System.Windows.Forms.Padding(5);
            imgBox.BackColor = Color.Gray;
            imgBox.Dock = DockStyle.Top;

            panelImgs.Controls.Add(imgBox);
            imgBox.Update();
        }

        //参数设置
        private void ColorSettings()
        {
            int ld = axSDK30001.Brightness;//亮度
            int dbd = axSDK30001.Contrast;//对比度
            int bhd = axSDK30001.Saturation;//饱和度
            int sd = axSDK30001.Hue;//色度
            int rd = axSDK30001.Sharpness;//锐度

            //Form_ColorSetting frm = new Form_ColorSetting(ld, dbd, bhd, sd, rd);
            //if (frm.ShowDialog() == DialogResult.OK)
            //{
            //    axSDK30001.Brightness = frm.ld;
            //    axSDK30001.Contrast = frm.dbd;
            //    axSDK30001.Saturation = frm.bhd;
            //    axSDK30001.Hue = frm.sd;
            //    axSDK30001.Sharpness = frm.rd;
            //}

        }

        //输出设置
        private void OutputSetting()
        {
            //if (cameraControl1.CameraCreated)
            //{
            //    cameraControl1.DisplayPropertyPage_SourcePinOutput(this.Handle);
            //}
        }

        //图像点击
        void imgBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Left) return;
            //图像选择事件
            foreach (var control in this.panelImgs.Controls)
            {
                if (control is PictureBox)
                {//将其它控件还原为默认样式
                    var imgBox = control as PictureBox;
                    imgBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
                    imgBox.BackColor = Color.Gray;
                }
            }

            //设置选择控件样式
            if (sender as PictureBox != null)
            {
                var picBox = ((PictureBox)sender);
                picBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                picBox.BackColor = Color.Blue;


                if (!picBox.Controls.ContainsKey("delBtn"))
                {
                    //显示编辑与删除按钮
                    var delButton = new Button();
                    delButton.Name = "delBtn";
                    delButton.Image = WoSoft.PACS.Win.Properties.Resources.delete2_samll;
                    delButton.Width = 20;
                    delButton.Height = 20;
                    delButton.BackColor = Color.Transparent;
                    delButton.Location = new Point(5, 5);
                    delButton.Click += new EventHandler(delButton_Click);
                    picBox.Controls.Add(delButton);
                }

                //如果没有图像编辑则加载
                if (!picBox.Controls.ContainsKey("imgEditBtn"))
                {
                    //显示编辑与删除按钮
                    var imgEditButton = new Button();
                    imgEditButton.Name = "imgEditBtn";
                    imgEditButton.Image = WoSoft.PACS.Win.Properties.Resources.img_edit;
                    imgEditButton.Width = 20;
                    imgEditButton.Height = 20;
                    imgEditButton.BackColor = Color.Transparent;
                    imgEditButton.Location = new Point(25, 5);
                    imgEditButton.Click += new EventHandler(imgBox_DoubleClick);
                    picBox.Controls.Add(imgEditButton);
                }
            }
        }

        //删除图像
        void delButton_Click(object sender, EventArgs e)
        {
            var r = MessageBoxEx.Show("您确认要删除选中的图像吗?", "删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (r == DialogResult.OK)
            {
                var btn = sender as Button;
                if (btn != null)
                {
                    var imgBox = btn.Parent;
                    imgBox.Parent.Controls.Remove(imgBox);
                    this.panelImgs.Update();

                    //触发删除事件
                    if (onDeleteImg != null)
                    {
                        onDeleteImg(imgBox.Name);
                    }
                }
            }
        }

        //图像双击
        void imgBox_DoubleClick(object sender, EventArgs e)
        {
            if (this.onDbClickImage != null)
            {
                var button = sender as Button;
                if (button != null)
                {
                    var imgBox = button.Parent as PictureBox;
                    if (imgBox != null)
                    {
                        onDbClickImage(imgBox.Image);
                    }
                }
            }
        }

        /// <summary>
        /// 关闭摄像头
        /// </summary>
        public void CloseCamera()
        {
            //try
            //{
            //    // Close camera
            //    cameraControl1.CloseCamera();
            //    cameraControl1.Refresh();

            //    this.tsbCapture.Enabled = false;
            //    this.tsbStop.Enabled = false;
            //    this.tsbSetting.Enabled = false;
            //    this.tsbOutputSetting.Enabled = false;
            //    this.tsbPlay.Enabled = true;
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}

            try
            {
                axSDK30001.Stop();
                this.camlock.Reset();
                this.running = false;
                if (this.camlock.WaitOne(2000))
                {
                    //释放资源
                    this.cam.Dispose();
                    this.thread = null;
                    this.cam = null;

                    this.tsbCapture.Enabled = false;
                    this.tsbStop.Enabled = false;
                    this.tsbPlay.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 1,4禁用,2,3启用
        /// </summary>
        /// <param name="state"></param>
        public void SetState(int state)
        {
            if (state == 1 || state == 4)
            {
                this.tsbPlay.Enabled = false;
                this.tsbCapture.Enabled = false;
                this.tsbStop.Enabled = false;
                this.tsbColorSetting.Enabled = false;
                this.tsbOutputSetting.Enabled = false;
            }
            else if (state == 2 || state == 3)
            {
                this.tsbPlay.Enabled = true;
                this.tsbCapture.Enabled = true;
                this.tsbStop.Enabled = true;
                this.tsbColorSetting.Enabled = true;
                this.tsbOutputSetting.Enabled = true;
            }
        }

        private void SaveSetting()
        {
            WoSoft.PACS.Win.Properties.Settings.Default.CameraVar = tlsPixs.SelectedIndex.ToString() + "|" + tlsImageSize.SelectedIndex.ToString() + "|" + tlsCapDevices.SelectedIndex.ToString();
            int ld = axSDK30001.Brightness;//亮度
            int dbd = axSDK30001.Contrast;//对比度
            int bhd = axSDK30001.Saturation;//饱和度
            int sd = axSDK30001.Hue;//色度
            int rd = axSDK30001.Sharpness;//锐度
            WoSoft.PACS.Win.Properties.Settings.Default.ColorSetting = ld.ToString() + "|" + dbd.ToString() + "|" + bhd.ToString() + "|" + sd.ToString() + "|" + rd.ToString();
            
            WoSoft.PACS.Win.Properties.Settings.Default.Save();
        }

        //注册热键的api 
        [DllImport("user32.dll")]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        public enum KeyModifiers //组合键枚举
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }

        /// <summary>
        /// 注册热键
        /// </summary>
        public void RegHotKey()
        {
            uint ctrHotKey = (uint)(KeyModifiers.Alt | KeyModifiers.Control);
            if (!RegisterHotKey(this.Handle, 8888, ctrHotKey, WoSoft.PACS.Win.Properties.Settings.Default.DefaultHotKey))
            {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode == 1409)
                {
                    MessageBox.Show("热键被占用 ！");
                }
                else
                {
                    MessageBox.Show("注册热键失败！错误代码：" + errorCode);
                }
            }
        }
        /// <summary>
        /// 取消注册热键
        /// </summary>
        public void UnRegHotKey()
        {
            UnregisterHotKey(this.Handle, 8888);
        }

        //调用API
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetForegroundWindow(); //获得本窗体的句柄
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x0312:    //这个是window消息定义的注册的热键消息 
                    if (m.WParam.ToString().Equals("8888"))  //热键消息 
                    {
                        bool b = SetForegroundWindow(this.Handle);
                        //MessageBox.Show("你按了热键"+this.Parent.Name+b.ToString());
                        this.CameraImage();//采集图像

                        Thread.Sleep(100);
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        public void HidePanelImg()//隐藏右边图片框
        {
            splitContainer1.Panel2Collapsed = true;
        }

        public void UnHidePanelImg()//取消隐藏右边图片框
        {
            splitContainer1.Panel2Collapsed = false;
        }
    }
}
